﻿
using Dal;
using Entity;
using Entity.DTO;
using IDal;
using System.Runtime.CompilerServices;
using System.Security.Principal;

namespace Bll
{
    /// <summary>
    /// 角色业务逻辑层
    /// </summary>
    public class RoleInfoBll : IRoleInfoBll
    {
        IRoleInfoDal _roleInfoDal;
        IUserInfoDal _userInfoDal;
        IMenuInfoDal _menuInfoDal;
        IUserInfoRoleInfoDal _userInfoRoleInfoDal;
        IRoleInfoMenuInfoDal _roleInfoMenuInfoDal;


        public RoleInfoBll(IRoleInfoDal roleInfoDal, IUserInfoDal userInfoDal, IMenuInfoDal menuInfoDal, IUserInfoRoleInfoDal r_UserInfo_RoleInfoDal, IRoleInfoMenuInfoDal r_RoleInfo_MenuInfoDal)
        {
            _roleInfoDal = roleInfoDal;
            _userInfoDal = userInfoDal;
            _menuInfoDal = menuInfoDal;
            _userInfoRoleInfoDal = r_UserInfo_RoleInfoDal;
            _roleInfoMenuInfoDal = r_RoleInfo_MenuInfoDal;
        }

        /// <summary>
        /// 获取穿梭框的备选数据，和已绑定的用户数据
        /// </summary>
        public object GetBindUserInfo(string roleId)
        {
            //备选数据
            var options = _userInfoDal.GetUserInfosDbSet().Where(u => !u.IsDelete).Select(u => new
            {
                Value = u.Id,
                Title = u.UserName,
            }).ToList();

            //已绑定的数据
            var bindUserIds = _userInfoRoleInfoDal.GetDbSet()
                .Where(r => r.RoleId == roleId).Select(r => r.UserId).ToList();

            return new
            {
                options,
                bindUserIds
            };
        }

        /// <summary>
        /// 为角色绑定用户
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="UserIds"></param>
        /// <returns></returns>
        public bool BindUserInfo(string roleId, List<string> userIds)
        {
            foreach (var userId in userIds)
            {

                UserInfoRoleInfo entity = new UserInfoRoleInfo()
                {
                    Id = Guid.NewGuid().ToString(),
                    CreateTime = DateTime.Now,
                    RoleId = roleId,
                    UserId = userId
                };

                _userInfoRoleInfoDal.CreateEntity(entity);
            }

            return true;
        }


        /// <summary>
        /// 创建角色
        /// </summary>
        /// <returns></returns>
        public bool CreateRoleInfo(string roleName, string description, out string msg)
        {
            RoleInfo roleInfo = _roleInfoDal.GetRoleInfosDbSet()
                .Where(d => d.RoleName == roleName).FirstOrDefault();

            if (roleInfo != null)
            {
                msg = "角色已经存在";
                return false;
            }

            //int count = roleInfoDal.GetRoleInfos().Count(u=> u.Account == account);
            //if (count > 0) 
            //{
            //    return false;
            //}


            RoleInfo entity = new RoleInfo();
            //创建guid 赋值给角色id，目的是保证id唯一
            entity.Id = Guid.NewGuid().ToString();
            entity.Description = description;
            entity.RoleName = roleName;
            entity.CreateTime = DateTime.Now;

            //调用数据访问层创建角色
            bool isSuccess = _roleInfoDal.CreateEntity(entity);

            if (isSuccess)
            {
                msg = "成功";
            }
            else
            {
                msg = "失败";
            }
            return isSuccess;
        }


        /// <summary>
        /// 软删除角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DeleteRoleInfo(string id)
        {
            RoleInfo roleInfo = _roleInfoDal.GetRoleInfosDbSet().FirstOrDefault(u => u.Id == id);
            if (roleInfo == null)
            {
                return false;
            }

            roleInfo.IsDelete = true;

            return _roleInfoDal.UpdateRoleInfo(roleInfo);
        }

        /// <summary>
        /// 批量软删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public bool DeleteRoleInfos(List<string> ids)
        {
            foreach (var id in ids)
            {
                RoleInfo roleInfo = _roleInfoDal.GetRoleInfosDbSet().FirstOrDefault(u => u.Id == id);
                if (roleInfo == null)
                {
                    return false;
                }

                roleInfo.IsDelete = true;

                _roleInfoDal.UpdateRoleInfo(roleInfo);
            }

            return true;
        }


        /// <summary>
        /// 根据角色id获取角色信息
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public RoleInfo GetRoleInfoById(string roleId)
        {
            return _roleInfoDal.GetRoleInfosDbSet().Where(u => u.Id == roleId).FirstOrDefault();
        }


        /// <summary>
        /// 获取角色集合
        /// </summary>
        public object GetRoleInfoList(string roleName, int page, int limit, out int count)
        {
            //内连接
            //var queryable = (from d in _roleInfoDal.GetRoleInfosDbSet()
            //         join u in _userInfoDal.GetUserInfosDbSet()
            //         on d.LeaderId equals u.Id
            //         select new
            //         {
            //             d.Id,
            //             d.RoleName,
            //             d.Description,
            //             d.CreateTime,
            //             //d.LeaderId,
            //             LeaderName = u.UserName,
            //             d.ParentId
            //         });

            //左连接
            var queryable = from r in _roleInfoDal.GetRoleInfosDbSet().Where(d => !d.IsDelete)  //角色
                            select new
                            {
                                r.Id,
                                r.RoleName,
                                r.Description,
                                r.CreateTime
                            };


            //IQueryable<RoleInfo> queryable = _roleInfoDal.GetRoleInfosDbSet().Where(u => !u.IsDelete).OrderByDescending(d => d.CreateTime);

            if (!string.IsNullOrEmpty(roleName))
            {
                queryable = queryable.Where(u => u.RoleName.Contains(roleName));
            }


            //查询总条数
            count = queryable.Count();

            var list = queryable
                .Select(d =>
                 new
                 {
                     d.Id,
                     d.RoleName,
                     d.Description,
                     d.CreateTime
                 }).OrderByDescending(d => d.CreateTime).Skip((page - 1) * limit).Take(limit).ToList().Select(d=> new 
                 {
                     d.Id,
                     d.RoleName,
                     d.Description,
                     CreateTime  = d.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")
                 });

            return list;
        }


        /// <summary>
        /// 更新角色
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="roleName"></param>
        /// <param name="description"></param>
        /// <returns></returns>
        public bool UpdateRoleInfo(string roleId, string roleName, string description,out string msg)
        {
            //根据账号找出角色的信息
            RoleInfo entity = _roleInfoDal.GetRoleInfosDbSet().FirstOrDefault(u => u.Id == roleId);
            if (entity == null)
            {
                msg = "未找到角色信息";
                return false;
            }

            //查询是否修改到其他的名字一样的情况
            RoleInfo otherEntity = _roleInfoDal.GetDbSet().FirstOrDefault(u => u.Id != roleId && u.RoleName == roleName);
            if (otherEntity != null)
            {
                msg = "此角色名字已存在";
                return false;
            }


            entity.RoleName = roleName;
            entity.Description = description;

            //调用数据访问层
            bool isSucess = _roleInfoDal.UpdateRoleInfo(entity);
            msg = "成功";
            return isSucess;
        }

        /// <summary>
        /// 为角色解除绑定用户
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="userIds"></param>
        /// <returns></returns>
        public bool UnbindUserInfo(string roleId, List<string> userIds)
        {
            foreach (var userId in userIds)
            {
                //查询出当前角色下绑定用户信息（中间表）
                var entity = _userInfoRoleInfoDal.GetDbSet().FirstOrDefault(r => r.UserId == userId && r.RoleId == roleId);
                if (entity != null)
                {
                    //解绑其实就是删除中间表的数据
                    //_userInfoRoleInfoDal.DeleteEntity(entity);

                    _userInfoRoleInfoDal.DeleteEntityById(entity.Id);
                }
            }

            //var entities = _userInfoRoleInfoDal.GetDbSet<UserInfoRoleInfo>().Where(r => userIds.Contains(r.UserId) && r.RoleId == roleId).ToList();
            //_userInfoRoleInfoDal.BatchDeleteEntity(entities);

            return true;
        }

        /// <summary>
        /// 获取穿梭框的备选数据，和已绑定的菜单数据
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public object GetBindMenuInfo(string roleId)
        {
            //备选数据
            var options = _menuInfoDal.GetDbSet().Where(m => !m.IsDelete).Select(u => new
            {
                Value = u.Id,
                Title = u.Title,
            }).ToList();

            //已绑定的数据
            var bindIds = _roleInfoMenuInfoDal.GetDbSet()
                .Where(r => r.RoleId == roleId).Select(r => r.MenuId).ToList();

            return new
            {
                options,
                bindIds
            };
        }

        /// <summary>
        /// 为角色解除绑定菜单
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="menuIds"></param>
        /// <returns></returns>
        public bool UnbindMenuInfo(string roleId, List<string> menuIds)
        {
            foreach (var menuId in menuIds)
            {
                //查询出当前角色下绑定用户信息（中间表）
                var entity = _roleInfoMenuInfoDal.GetDbSet().FirstOrDefault(r => r.MenuId == menuId && r.RoleId == roleId);
                if (entity != null)
                {
                    //解绑其实就是删除中间表的数据
                    //_userInfoRoleInfoDal.DeleteEntity(entity);

                    _roleInfoMenuInfoDal.DeleteEntityById(entity.Id);
                }
            }

            return true;
        }

        /// <summary>
        /// 为角色绑定菜单
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="menuIds"></param>
        /// <returns></returns>
        public bool BindMenuInfo(string roleId, List<string> menuIds)
        {
            foreach (var menuId in menuIds)
            {
                RoleInfoMenuInfo entity = new RoleInfoMenuInfo()
                {
                    Id = Guid.NewGuid().ToString(),
                    CreateTime = DateTime.Now,
                    RoleId = roleId,
                    MenuId = menuId
                };

                _roleInfoMenuInfoDal.CreateEntity(entity);
            }

            return true;
        }
    }
}